# coding: utf-8

from datetime import datetime
import requests
import json
import pandas as pd
import os


class TradeCal(object):
    cal_file = os.path.join(os.getcwd(), "data", "Calendar.json")

    def __init__(self, number=24):   # 默认取最近24个月的交易日历
        self.calendar = pd.DataFrame()
        self.set_up(number=number)   #

    def read_calendar(self, number: int):
        # 深交所
        url_p = """http://www.szse.cn/api/report/exchange/onepersistenthour/monthList?month={month}"""
        now = datetime.now()
        year = now.year
        month = now.month

        # 读取json文件
        with open(self.cal_file, "r") as f:
            calendar = json.load(f)

        headers = {
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "Connection": "keep-alive",
            "Content-Type": "application/json",
            "Host": "www.szse.cn",
            "Referer": "http://www.szse.cn/www/aboutus/calendar/",
            "User-Agent": """Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.57""",
            "X-Request-Type": "ajax",
            "X-Requested-With": "XMLHttpRequest"
        }
        write = False
        for num in range(number):
            year_month = str(year) + "-" + str(month).rjust(2, "0")
            if calendar.get(year_month) is None:
                url = url_p.format(month=year_month)
                response = requests.get(url, headers=headers)
                res = json.loads(response.text)
                res = res["data"]
                calendar[year_month] = res
                write = True
            month = month - 1
            if month == 0:
                year = year - 1
                month = 12

        if write:
            json_str = json.dumps(calendar)
            with open(self.cal_file, "w") as json_file:
                json_file.write(json_str)
        return calendar

    def set_up(self, number: int):
        cal_dict = self.read_calendar(number=number)  # 从深交所、文件中读取最近number个月的交易日历
        self.calendar = self.change_format(cal_dict)   #

    @property
    def calender(self):
        return self.calendar

    @staticmethod
    def change_format(cal_dict: dict):
        df_res = pd.DataFrame()
        for v, k in cal_dict.items():
            df = pd.DataFrame(k)
            df_res = pd.concat([df_res, df], ignore_index=True)

        df_res["is_open"] = df_res["jybz"].astype(int)
        df_res["cal_date"] = df_res["jyrq"].str.replace("-", "")
        df_res = df_res[["cal_date", "is_open"]]
        df_res.sort_values(by="cal_date", ascending=False, inplace=True)
        return df_res


if __name__ == '__main__':
    a = TradeCal(number=216)
    print(a.calendar)
